<template>
  <div class="cart combground">
    <div class="container">
      <div class="comtitle"><h2 class="comh2">购物车</h2></div>
      <div class="content">
        <div class="title">
          <div class="allSelect f14" @click="selectAll">
            <div class="checkItem" :class="allCartIdArr.length === selectArr.length && selectArr.length > 0 ? 'active' : ''"></div>
            全选
          </div>
          <div class="remove" @click="showTc('delSelect')">删除选中的产品</div>
          <div class="clear" @click="showTc('clear')">清空购物车</div>
        </div>
        <div class="table-wrap">
          <div class="item-wrap" v-for="(item, index) in cart" :key="index">
            <div class="storeName">商家：{{ item.mer_name }}</div>
            <Table class="table-head">
              <table-column label="商品信息" align="center" width="360" />
              <table-column label="商品单价" align="center" />
              <table-column label="数量" align="center" />
              <table-column label="小计" align="center" />
              <table-column label="操作" align="center" />
            </Table>
            <Table ref="table" :data="item.list" :show-header="false" border>
              <table-column type="index" width="80" align="center">
                <template v-slot="{ row }">
                  <div class="checkItem transition" :class="selectArr.includes(row.cart_id) ? 'active' : ''" @click="select(row.cart_id)"></div>
                </template>
              </table-column>
              <table-column prop="name" label="商品信息" align="center" width="280">
                <template v-slot="{ row }">
                  <div class="table-name">
                    <img :src="row.product && row.product.image" alt="" class="pic" />
                    <p class="name">{{ row.product && row.product.store_name }}</p>
                  </div>
                </template>
              </table-column>
              <table-column prop="price" label="商品单价" align="center">
                <template v-slot="{ row }">
                  ￥{{ row.product && row.product_price }}
                </template>
              </table-column>
              <table-column prop="number" label="数量" align="center">
                <template v-slot="{ row }">
                  <div style="display: flex; justify-content: center">
                    <InputNumber v-model="row.cart_num" :data-id="row.cart_id" :data-index="index" :min="row.product && row.product.moq" :max="999" @change="handleChange(row)" />
                  </div>
                </template>
              </table-column>
              <table-column prop="price" label="小计" align="center">
                <template v-slot="{ row }">
                  <span style="color: #e48b2c">￥{{ row.count }}</span>
                </template>
              </table-column>
              <table-column prop="operation" label="操作" align="center">
                <template v-slot="{ row }">
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      cursor: pointer;
                    "
                    @click="deleteCart('dan', row.cart_id)"
                  >
                    <img src="~/assets/images/delete-btn.png" alt="" />
                    <!-- 删除 -->
                  </div>
                </template>
              </table-column>
            </Table>
            <div class="total" v-if="item.sum">
              分项合计：
              <span class="keywords">￥ {{ item.sum }}</span>
            </div>
          </div>
          <nodata message="暂无商品" :status="listStatus"></nodata>
          <div class="tail">
            <div class="chosen">
              已选商品
              <div class="keywords">{{ selectArr.length }}</div>
              件
            </div>
            <div class="total-and-pay">
              <span class="total">应付总额：￥{{ countPrice }}</span>
              <m-button width="122" type="light" @click="goPay"><span class="pay-inner">去结算</span></m-button>
            </div>
          </div>
        </div>
      </div>

      <div class="history">
        <div class="title">
          <span class="text">浏览历史</span>
          <div class="line"></div>
          <span class="more" @click="$router.push('/profile/collection-history/browsing-history')">
            查看更多
            <img src="~/assets/images/modo.png" />
          </span>
        </div>
        <div class="list">
          <product-item
            class="item"
            :price="item.product && item.product.price"
            :productId="item.product && item.product.product_id"
            :storage="item.product && item.product.moq"
            :image="item.product && item.product.image"
            :name="item.product && item.product.store_name"
            v-for="(item, index) in history"
            :key="index"
          />
        </div>
      </div>
    </div>
    <!-- 平台提示 -->
    <m-dialog title="平台提示" :show-dialog.sync="showDialog">
      <div class="text f16 textcenter mbt30">{{ showMsg }}</div>
      <div class="btns" style="display: flex; justify-content: center">
        <m-button width="180" type="dark" @click="closeTc" style="margin-right: 10px">取消</m-button>
        <m-button width="180" @click="confirm">确定</m-button>
      </div>
    </m-dialog>
  </div>
</template>

<script>
import MCheckbox from '@/components/common/m-checkbox/MCheckbox';
import MInput from '@/components/common/m-input/MInput';
import MButton from '@/components/common/m-button/MButton';
import ProductItem from '@/components/common/ProductItem';
import MDialog from '@/components/common/m-dialog/MDialog';
import { Table, TableColumn, InputNumber } from 'element-ui';
import { myCart, myHistory, delCart, updateCart, clearCart } from '@/request/api';

export default {
  name: 'Cart',
  components: {
    ProductItem,
    MButton,
    MInput,
    MCheckbox,
    Table,
    TableColumn,
    MDialog,
    InputNumber
  },
  data() {
    return {
      cart: [],
      listStatus: 1,
      fail: [],
      history: [],
      showDialog: false,
      showMsg: '',
      allCartIdArr: [],
      selectArr: [],
      countPrice: 0,
      option: ''
    };
  },
  created() {
    this.getCartList();
    this.getHistory();
  },
  methods: {
    /** 去支付 */
    goPay() {
      if (this.selectArr.length == 0) {
        return this.$toastVant('请先选择购买产品');
      }
      let arrSting = this.$common.arrToString(this.selectArr);
      this.$router.push({
        name: 'CateProductOrder',
        query: { cart_id: arrSting, is_cart: 1 }
      });
    },
    showTc(option) {
      switch (option) {
        case 'clear':
          this.showMsg = '确定清空购物车?';
          break;
        case 'delSelect':
          this.showMsg = '确定删除所选产品？';
          break;
      }
      this.showDialog = true;
      this.option = option;
    },
    confirm() {
      if (this.option == 'clear') {
        this.clearAllCart();
      } else if (this.option == 'delSelect') {
        this.deleteCart();
      }
    },
    closeTc() {
      this.option = '';
      this.showDialog = false;
    },
    /** 多选 */
    selectAll() {
      let arr = this.allCartIdArr;
      if (this.selectArr == arr) {
        this.selectArr = [];
      } else {
        this.selectArr = arr;
        for (const i in this.cart) {
          this.countStorePrice(i);
        }
      }
    },
    select(id) {
      var arr = JSON.parse(JSON.stringify(this.selectArr));
      var has = false;
      var index;
      arr.forEach((item, i) => {
        if (item == id) {
          has = true;
          index = i;
        }
      });
      if (has) {
        arr.splice(index, 1);
      } else {
        arr.push(id);
      }
      this.selectArr = arr;
      this.countStorePrice();
    },
    countProductPrice(price) {
      for (var i in this.cart) {
        for (var j in this.cart[i].list) {
          this.cart[i].list[j].count = parseInt(this.cart[i].list[j].cart_num) * parseFloat(this.cart[i].list[j].product_price);
        }
        this.countStorePrice(i);
      }
    },
    /**
     * @param {Object} row
     * 更改购物车商品数量
     */
    handleChange(row) {
      if (row.cart_num <= 0) {
        return this.$toastVant.fail('数量不正确！');
      }
      const data = {
        id: row.cart_id,
        cart_num: row.cart_num
      };
      updateCart(data)
        .then(res => {
          if (res.status === 200) {
            this.countProductPrice();
            this.$toastVant.success(res.message);
          }
        })
        .catch(err => {
          this.getCartList();
          this.$message.error(err.message);
        });
    },
    /** 计算总数量*/
    countStorePrice() {
      for (var i in this.cart) {
        var sum = 0;
        this.cart[i].list.forEach((item, j) => {
          if (this.selectArr.includes(item.cart_id)) {
            sum += item.count;
          }
        });
        this.cart[i].sum = sum;
      }
      this.countAllPrice();
    },
    /** 计算总价格 */
    countAllPrice() {
      var count = 0;
      for (var i in this.cart) {
        count += this.cart[i].sum || 0;
      }
      this.countPrice = count;
    },
    /** 获取购物车列表*/
    getCartList() {
      myCart()
        .then(res => {
          if (res.status === 200) {
            for (var i in res.data.list) {
              for (var j in res.data.list[i].list) {
                this.allCartIdArr.push(res.data.list[i].list[j].cart_id);
                res.data.list[i].list[j].count =
                parseInt(res.data.list[i].list[j].cart_num) * parseFloat(res.data.list[i].list[j].product_price);
              }
            }
            this.cart = res.data.list;
            this.fail = res.data.fail;
            if (this.cart.length > 0) {
              this.listStatus = 2;
            } else {
              this.listStatus = 0;
            }
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    /**
     * 删除购物车
     * @param type
     * @param id
     */
    deleteCart(type, id) {
      let that = this;
      let data = '';
      if (type == 'dan') {
        data = { cart_id: [id] };
      } else {
        data = { cart_id: this.selectArr};
      }
      this.$toastVant.loading('请稍后');
      delCart(data)
        .then(res => {
          if (res.status === 200) {
            this.$toastVant.success('删除成功！');
            setTimeout(function() {
              that.$router.go(0);
            }, 500);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    /** 清空购物车*/
    clearAllCart() {
      this.$toastVant.loading('请稍后');
      delCart().then(async res => {
          if (res.status === 200) {
            this.$toastVant('购物车已清空！');
            setTimeout(function() {
              that.$router.go(0);
            }, 500);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    getHistory() {
      myHistory()
        .then(res => {
          if (res.status === 200) {
            this.history = res.data.list;
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~@/assets/style/common.scss';

.cart {
  padding: 50px 0 30px 0;

  .storeName {
    font-size: 15px;
    padding: 10px 20px;
    line-height: 30px;
    color: #333;
  }

  .content {
    padding: 65px 50px;
    margin-top: 50px;
    font-size: 16px;
    color: #666;
    background-color: #fff;
    margin-bottom: 50px;

    .checkItem {
      width: 20px;
      height: 20px;
      border: 1px solid #ccc;
      margin: 0 auto;
      cursor: pointer;
      border-radius: 3px;
      position: relative;
    }

    .checkItem.active {
      background: $theme-color-1;
      border-color: $theme-color-1;
    }

    .checkItem.active:after {
      content: '';
      border: 2px solid #fff;
      border-left: 0;
      border-top: 0;
      height: 9px;
      left: 6px;
      position: absolute;
      top: 2px;
      transform: rotate(45deg);
      width: 4px;
      transition: transform 0.15s ease-in 0.05s;
      transform-origin: center;
    }

    .allSelect {
      padding-left: 30px;
      position: relative;
      line-height: 22px;
      cursor: pointer;

      .checkItem {
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    > .title {
      display: flex;
      align-items: center;
      margin-bottom: 30px;

      .remove,
      .clear {
        cursor: pointer;
        margin-left: 30px;
        font-size: 14px;
      }
    }

    .table-wrap {
      color: #666;
      font-size: 16px;

      margin-right: -1px;

      .table-head {
        /deep/ table {
          width: 1100px !important;
          background-color: #f3f4f7;
        }

        /deep/ .el-table__body-wrapper {
          height: 0;
        }

        /deep/ th {
          color: #666;
          background-color: #f3f4f7;
          border-bottom: none;
          padding: 10px 0;
        }
      }

      /deep/ table {
        width: 1100px !important;
      }

      /deep/ .el-table {
        border: none;
      }

      /deep/ .el-table::before {
        display: none;
      }

      /deep/ .el-table::after {
        display: none;
      }

      /deep/ td {
        border: none;
        border-bottom: 1px solid #f3f4f7;
      }

      /deep/ .el-checkbox__inner {
        width: 20px;
        height: 20px;
        border-radius: 5px;
        text-align: center;
      }

      /deep/ .el-checkbox__inner::after {
        height: 12px;
        left: 5px;
        top: 0;
        width: 6px;
      }

      /deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
        background: #fbf2e9;
      }

      /deep/ .el-input__inner {
        text-align: center;
      }

      .item-wrap {
        margin-top: -2px;

        /deep/ .el-checkbox__input.is-checked {
          .el-checkbox__inner {
            background-color: $theme-color-1;
            border-color: $theme-color-1;
          }
        }

        /deep/ .el-checkbox__input.is-focus {
          .el-checkbox__inner {
            border-color: $theme-color-1;
          }
        }

        /deep/ .el-checkbox__inner:hover {
          border-color: $theme-color-1;
        }

        .title {
          margin-top: 15px;
          margin-bottom: 15px;
        }

        .table-name {
          display: flex;
          align-items: center;

          .pic {
            width: 140px;
            height: 140px;
            margin-right: 15px;
            object-fit: cover;
          }
        }

        > .total {
          padding: 15px 20px;
          background-color: rgb(243, 244, 247);
          display: flex;
          justify-content: flex-end;

          .keywords {
            font-size: 18px;
            font-weight: bold;
          }
        }
      }

      .item-wrap {
        border: solid 1px #eaeaea;
        margin-bottom: 30px;
      }

      .tail {
        padding: 15px 20px;
        background-color: $theme-color-1;
        font-size: 16px;
        color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .chosen {
          display: flex;
          align-items: center;

          .keywords {
            font-size: 20px;
            font-weight: bold;
            padding: 5px;
          }
        }

        .total-and-pay {
          display: flex;
          align-items: center;

          .total {
            font-weight: bold;
            font-size: 22px;
            margin-right: 30px;
          }

          .pay-inner {
            font-size: 18px;
            font-weight: bold;
            color: $theme-color-1;
          }
        }
      }
    }
  }

  .history {
    color: #666;
    font-size: 16px;
    margin-bottom: 50px;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;

      .text {
        width: 90px;
      }

      .more {
        color: $theme-color-1;
        cursor: pointer;
      }

      .line {
        width: calc(100% - 190px);
        height: 6px;
        background-color: rgb(231, 232, 233);
      }
    }

    .list {
      margin: -10px;
      width: 1200px;
      margin: 0 auto;
      padding-left: 15px;

      .item {
        width: 175px;
        margin: 10px;
      }
    }
  }
}
</style>
